package cn.edu.zust.se.service.share.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class PlusMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        // 插入时填充的字段处理
        this.setFieldValByName("createBy", getCurrentUserId(), metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", getCurrentUserId(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新时填充的字段处理
        this.setFieldValByName("updateBy", getCurrentUserId(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
    }

    private Long getCurrentUserId() {
        Long loginId = Long.parseLong((String) StpUtil.getLoginId()) ;
        if (loginId == null) {
            log.info("当前用户未登录");
        }
        return loginId;
    }
}
